package com.ruoyi.flowable.common;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class TaskFileUtils {

    public static void  replaceBlobUrlWithResponseUrls(Map<String, Object> variables) {
        if (variables != null && !variables.isEmpty()) {
            variables.forEach((key, value) -> {
                if (key.endsWith("Picture") || key.endsWith("File")) {
                    replaceBlobUrlWithResponseUrl(variables, key);
                }
            });
        }
    }

    /**
     * 替换图片变量中的 url 为 response.url，并重新放回 variables 中
     *
     * @param variables 流程变量 Map
     * @param key       要处理的键名，如 "projectPicture", "zzPicture" 等
     */
    public static void replaceBlobUrlWithResponseUrl(Map<String, Object> variables, String key) {
        Object pictureObj = variables.get(key);
        if (pictureObj == null) {
            return;
        }

        if (pictureObj instanceof List<?>) {
            List<?> pictureList = (List<?>) pictureObj;
            if (!pictureList.isEmpty() && pictureList.get(0) instanceof Map<?, ?>) {
                Map<String, Object> pictureMap = (Map<String, Object>) pictureList.get(0);

                @SuppressWarnings("unchecked")
                Map<String, Object> responseMap = (Map<String, Object>) pictureMap.get("response");

                if (responseMap != null && responseMap.containsKey("url")) {
                    String newUrl = (String) responseMap.get("url");
                    pictureMap.put("url", newUrl); // 替换 url

                    // 构建新的列表并放回 variables
                    List<Map<String, Object>> newList = new ArrayList<>();
                    newList.add(pictureMap);
                    variables.put(key, newList);
                }
            }
        } else if (pictureObj instanceof Map<?, ?>) {
            // 如果是单个 Map 类型的情况
            Map<String, Object> pictureMap = (Map<String, Object>) pictureObj;

            @SuppressWarnings("unchecked")
            Map<String, Object> responseMap = (Map<String, Object>) pictureMap.get("response");

            if (responseMap != null && responseMap.containsKey("url")) {
                String newUrl = (String) responseMap.get("url");
                pictureMap.put("url", newUrl); // 替换 url

                variables.put(key, pictureMap);
            }
        }
    }
}
